import { AxiosResponse, InternalAxiosRequestConfig } from './types'
import { ElMessage } from 'element-plus'
import { SUCCESS_CODE } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (config.method === 'get') {
    if (config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
      config.params = {}
    }
  }
  console.log(config)
  return config
}

const defaultResponseInterceptors = (response: AxiosResponse) => {
  const config = response?.config
  const res = response?.data
  if (config.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (res.code === SUCCESS_CODE) {
    // 解密
    // 判断是否在白名单内
    return res
  } else {
    console.log(res.msg)

    ElMessage.error(res.msg)
    console.log(res.code)
    if (res.code === 401 || res.code === 400) {
      const userStore = useUserStoreWithOut()
      userStore.logout()
    }
  }
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
